#include "wm_hal.h"

DMA_HandleTypeDef hdma_sd_tx;
DMA_HandleTypeDef hdma_sd_rx;

extern void Error_Handler(void);

void HAL_MspInit(void)
{

}

void HAL_SD_MspInit(SD_HandleTypeDef *hsd)
{
	if (hsd->Instance == SD)
	{
		__HAL_RCC_SDIO_CLK_ENABLE();
		__HAL_RCC_GPIO_CLK_ENABLE();
		__HAL_RCC_DMA_CLK_ENABLE();
		
		__HAL_AFIO_REMAP_SDIO_CLK(GPIOB, GPIO_PIN_6);
		__HAL_AFIO_REMAP_SDIO_CMD(GPIOB, GPIO_PIN_7);
		__HAL_AFIO_REMAP_SDIO_D0(GPIOB, GPIO_PIN_8);
		__HAL_AFIO_REMAP_SDIO_D1(GPIOB, GPIO_PIN_9);
		__HAL_AFIO_REMAP_SDIO_D2(GPIOB, GPIO_PIN_10);
		__HAL_AFIO_REMAP_SDIO_D3(GPIOB, GPIO_PIN_11);
		
		// 多块读写的时候要用到DMA
		hdma_sd_tx.Instance = DMA_Channel0;
		hdma_sd_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
		hdma_sd_tx.Init.DestInc = DMA_DINC_DISABLE;
		hdma_sd_tx.Init.SrcInc = DMA_SINC_ENABLE;
		hdma_sd_tx.Init.DataAlignment = DMA_DATAALIGN_WORD;
		hdma_sd_tx.Init.Mode = DMA_MODE_NORMAL_SINGLE;
		hdma_sd_tx.Init.RequestSourceSel = DMA_REQUEST_SOURCE_SDIO;
		
		if (HAL_DMA_Init(&hdma_sd_tx) != HAL_OK)
		{
			Error_Handler();
		}
		__HAL_LINKDMA(hsd, hdmatx, hdma_sd_tx);
		
		hdma_sd_rx.Instance = DMA_Channel1;
		hdma_sd_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
		hdma_sd_rx.Init.DestInc = DMA_DINC_ENABLE;
		hdma_sd_rx.Init.SrcInc = DMA_SINC_DISABLE;
		hdma_sd_rx.Init.DataAlignment = DMA_DATAALIGN_WORD;
		hdma_sd_rx.Init.Mode = DMA_MODE_NORMAL_SINGLE;
		hdma_sd_rx.Init.RequestSourceSel = DMA_REQUEST_SOURCE_SDIO;
		
		if (HAL_DMA_Init(&hdma_sd_rx) != HAL_OK)
		{
			Error_Handler();
		}
		__HAL_LINKDMA(hsd, hdmarx, hdma_sd_rx);
	}
}